package models;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Question;

public class QuestionModel {
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "question_";

	private static QuestionModel instance = null;

	public static QuestionModel getInstance() {
		if (instance == null) {
			instance = new QuestionModel();
		}

		return instance;
	}

	private QuestionModel() {
		try {
			ObjectifyService.register(Question.class);
		} catch (Exception e) {
		}
		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			//e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}

	public List<Question> list(int page, int limit) {
		List<Question> questions = new ArrayList<Question>();

		String cacheName = prefix + "_page_" + page + "_limit_" + limit;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				questions = (List<Question>) cache.get(cacheName);
				if (questions != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			int start = (page - 1) * limit;
			questions = ofy.query(Question.class).filter("created !=", "null")
						.order("-created").limit(limit).offset(start).list();
			
			if (cache != null) {
				try {
					cache.put(cacheName, questions);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
			if (questions.size() == 0 ) {
				cacheName = prefix + "oldest_question";
				isCached = false;
				if (cache != null) {
					try {
						questions = (List<Question>) cache.get(cacheName);
						if (questions != null) isCached = true;
					} catch (Exception e) {
					}
				}
				
				if (!isCached) {
					questions = ofy.query(Question.class).filter("created !=", "null")
									.order("created").limit(limit).list();
					
					if (cache != null) {
						try {
							cache.put(cacheName, questions);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
		}
		
		if (questions == null) {
			questions = new ArrayList<Question>();
		}

		return questions;
	}

	public List<Question> listByCategory(String id, int page, int limit) {
		List<Question> questions = new ArrayList<Question>();

		String cacheName = prefix + "_category_" + id + "_page_" + page
				+ "_limit_" + limit;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				questions = (List<Question>) cache.get(cacheName);
				if (questions != null) isCached = true;
			} catch (Exception e) {
			}
		}
		
		if (!isCached) {
			int start = (page - 1) * limit;
			questions = ofy.query(Question.class).filter("category", id)
							.limit(limit).offset(start).list();
			
			if (cache != null) {
				try {
					cache.put(cacheName, questions);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
			if (questions.size() == 0 ) {
				cacheName = prefix + "oldest_question_category_" + id;
				isCached = false;
				if (cache != null) {
					try {
						questions = (List<Question>) cache.get(cacheName);
						if (questions != null) isCached = true;
					} catch (Exception e) {
					}
				}
				
				if (!isCached) {
					questions = ofy.query(Question.class).filter("category", id)
									.filter("created !=", "null").order("-created")
									.limit(limit).list();
					
					if (cache != null) {
						try {
							cache.put(cacheName, questions);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
		}
		
		if (questions == null) {
			questions = new ArrayList<Question>();
		}
		
		return questions;
	}

	public List<Question> getByListIds(List<String> ids) {
		List<Question> questions = new ArrayList<Question>();

		for (String id : ids) {
			Question question = getQuestion(id);
			if (question != null) {
				questions.add(question);
			}
		}

		return questions;
	}

	public void insert(Question question) {
		ofy.put(question);
	}

	public void delete(Question question) {
		ofy.delete(question);
	}

	public Question getQuestion(String id) {
		Question question = new Question();
		try {
			question = ofy.get(new Key<Question>(Question.class, id));
		} catch (Exception e) {
			question = null;
		}
		return question;
	}

	public Question getQuestionByUrl(String url) {
		Question question = new Question();
		
		String cacheName = prefix + url;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				question = (Question) cache.get(cacheName);
				if (question != null) isCached = true;
			} catch (Exception e) {
			}

		}
		if (!isCached) {
			try {
				question = ofy.query(Question.class).filter("url", url).get();
			} catch (Exception e) {
				question = null;
			}
			
			if (cache != null && question != null) {
				cache.put(cacheName, question);
			}
		}
		return question;
	}

	public boolean checkQuestionExists(String id) {
		boolean exists = false;
		Question question = getQuestion(id);
		if (question != null) {
			exists = true;
		}
		return exists;
	}

	public boolean checkQuestionExistsByUrl(String url) {
		boolean exists = false;
		Question question = getQuestionByUrl(url);
		if (question != null) {
			exists = true;
		}
		return exists;
	}
}
